package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.common.WebDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.Article;
import com.rockcent.mall.lib.domain.ArticleCategory;
import com.rockcent.mall.lib.dto.ArticleDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.ArticleCategoryRepository;
import com.rockcent.mall.lib.repository.ArticleRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Antinomy on 16/8/23.
 */
@RestController
public class ArticleController  extends BaseController {

    private final Logger log = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private Validator validator;

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private ArticleCategoryRepository articleCategoryRepository;

     /**
     *
     * @api {get} /mall/help_center/article/listCategory  某分类下的文章列表
     * @apiGroup mall_helpCenter
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} categoryId <code>必须参数</code> 分类ID
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     *    "data": [
     *        {
     *          "id": 17,
     *          "dateCreated": "2016-09-09 15:19:35",
     *          "lastUpdated": "2016-10-28 15:42:17",
     *          "name": "如何注册",
     *          "keyword": "如何注册",
     *          "content": "<p>如何注册如何注册如何注册如何注册如何注册如何注册如何注册<br></p>",
     *          "displayOrderId": 1,
     *          "mallId": 1,
     *          "parentCategoryId": 28,
     *          "parentCategoryText": "商家入驻",
     *          "categoryId": 29,
     *          "categoryText": "如何注册",
     *          "clickCounts": 24
     *        }
     *    ],
     *    "totalCount": 1,
     *    "totalPage": 1,
     *    "pageNo": 0,
     *    "pageSize": 10,
     *    "url": "/mall/help_center/article/listCategory",
     *    "prevUrl": "/mall/help_center/article/listCategory?pageNo=0&pageSize=10",
     *    "nextUrl": "/mall/help_center/article/listCategory?pageNo=0&pageSize=10"
     *    }
     * }
     */
    @RequestMapping(value = Routes.MALL_ARTICLE_LIST_CATEGORY, method = RequestMethod.GET)
    public JsonResult listUnderCategory(HttpServletRequest request, ArticleDto articleDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = result -> {

            if(articleDto.getCategoryId() == null){
                result.errorParam(Article.CHECK_ID_IS_NOT_NULL, log);
                return;
            }

            PageResult pageResult = getPage(articleDto.getPageNo(), articleDto.getPageSize());
            PageResult<ArticleDto> page = articleRepository.findArticlePageByCategoryId(pageResult, articleDto.getCategoryId(),userInfoDto.mall.getId());
            page.setUrl(Routes.MALL_ARTICLE_LIST_CATEGORY);

            result.data = page;
        };

        return doing.go(request, log);
    }


    /**
     *
     * @api {get} /mall/help_center/article/show 查看文章
     * @apiGroup mall_helpCenter
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *  @apiParam {Long} id <code>必须参数</code> 文章ID
     * @apiSuccessExample {json} Success-Response:
     * {
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *      "parentCategory": "商家入驻",
     *      "article":
     *      {
     *          "id": 17,
     *          "dateCreated": "2016-09-09 15:19:35",
     *          "lastUpdated": "2016-10-13 11:25:09",
     *          "version": 22,
     *          "name": "如何注册",
     *          "keyword": "如何注册",
     *          "displayOrderId": 1,
     *          "mallId": 1,
     *          "parentCategoryId": 28,
     *          "categoryId": 29,
     *          "content": "<p>如何注册如何注册如何注册如何注册如何注册如何注册如何注册<br></p>",
     *          "clickCounts": 22
     *      }
     *    }
     *}
     */
    @RequestMapping(value = Routes.MALL_ARTICLE_SHOW, method = RequestMethod.GET)
    public JsonResult show(ArticleDto articleDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        RestDoing doing = result -> {
            if(articleDto.getId() == null){
                result.errorParam(Article.CHECK_ID_IS_NOT_NULL, log);
                return;
            }

            Article article = articleRepository.findOne(articleDto.getId());

            if(article == null){
                result.errorParam(Article.REMIND_RECORD_IS_NOT_EXIST, log);
                return;
            }

            article.setClickCounts(article.getClickCounts()+1);
            articleRepository.save(article);

            HashMap resultMap = new HashMap();

            ArticleCategory category = articleCategoryRepository.findOne(article.getParentCategoryId());
            resultMap.put("article",article);
            resultMap.put("parentCategory",category.getName());

            result.data = resultMap;
        };

        return doing.go( request, log);
    }



    /**
     * 文章分类总览
     *
     */
    @RequestMapping(value = Routes.MALL_ARTICLE_OVERVIEW, method = RequestMethod.GET)
    public JsonResult overview(HttpServletRequest request, Long parentId) {
        RestDoing doing = result -> {
            UserInfoDto userInfoDto = userHelper.getSession(request);
            Long mallId = userInfoDto.mall.getId();

            List<ArticleCategory> categorys_1st = articleCategoryRepository.findAllByMallIdAndIsDeleteAndParentId(
                    mallId, Whether.NO, null
            );

            List resultList = new ArrayList<>();

            for (ArticleCategory category : categorys_1st) {
                HashMap item = new HashMap();
                item.put("category", category.getName());
                item.put("categoryId", category.getId());

                List<Article> articles = articleRepository.findByMallIdAndCategoryIdAndIsDelete(
                        mallId, category.getId(),Whether.NO);

                item.put("articles", articles);

                resultList.add(item);
            }

            result.data = resultList;
        };

        return doing.go(request, log);
    }

    /**
     * 文章分类标题查看
     */
    @RequestMapping(value = Routes.MALL_ARTICLE_CATEGORY, method = RequestMethod.GET)
    public String categoryPage(HttpServletRequest request, Model model) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        WebDoing<String> doing = (req, mod, viewData) -> {
            mod.addAttribute("mallId", userInfoDto.mall.getId());
            viewData.view = Routes.MALL_ARTICLE_CATEGORY;
        };

        return doing.go(request, model, log).view;
    }

    /**
     * 文章查看
     */
    @RequestMapping(value = Routes.MALL_ARTICLE_SHOW_PAGE, method = RequestMethod.GET)
    public String showPage(HttpServletRequest request, Model model) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        WebDoing<String> doing = (req, mod, viewData) -> {
            mod.addAttribute("mallId", userInfoDto.mall.getId());
            viewData.view = Routes.MALL_ARTICLE_SHOW_PAGE;
        };

        return doing.go(request, model, log).view;
    }

    /**
     * 文章分类预览
     *
     */
    @RequestMapping(value = Routes.MALL_ARTICLE_OVERVIEW_PAGE, method = RequestMethod.GET)
    public String overviewPage(HttpServletRequest request, Model model) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        WebDoing<String> doing = (req, mod, viewData) -> {
            mod.addAttribute("mallId", userInfoDto.mall.getId());
            viewData.view = Routes.MALL_ARTICLE_OVERVIEW_PAGE;
        };

        return doing.go(request, model, log).view;
    }

    /**
     * 文章分类预览
     */
    @RequestMapping(value = Routes.ARTICLE_OVERVIEW_PAGE, method = RequestMethod.GET)
    public String articlePage(HttpServletRequest request, Model model) {
        UserInfoDto userInfoDto = userHelper.getSession(request);

        WebDoing<String> doing = (req, mod, viewData) -> {
            mod.addAttribute("mallId", userInfoDto.mall.getId());
            viewData.view = Routes.ARTICLE_OVERVIEW_PAGE;
        };

        return doing.go(request, model, log).view;
    }

/**
 *
 * @api {get} /mall/help_center/article/search 搜索文章
 * @apiGroup mall_helpCenter
 * @apiVersion 1.0.0
 * @apiHeader {String} userToken 用户token
 * @apiHeader {String} domain    请求域名
 * @apiParam {String} keyword <code>必须参数</code> keyword
 * @apiSuccessExample {json} Success-Response:
 *  {
 *  "code": "1",
 *  "desc": "成功",
 *  "data":
 *   [
 *    {
 *    "id": 17,
 *    "name": "如何注册"
 *    }
 *  ]
 *  }
 */
    @RequestMapping(value = Routes.MALL_ARTICLE_SEARCH, method = RequestMethod.GET)
    public JsonResult searchArticle(HttpServletRequest request,ArticleDto articleDto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(articleDto.getKeyword())) {
                jsonResult.remind("keyword 不能为空",log);
                return;
            }
            List<ArticleDto> result=this.articleRepository.searchArticlByKeyword(userInfoDto.mall.getId(),articleDto.getKeyword());
            jsonResult.data=result;
        };
        return doing.go(request,log);
    }
}
